import { getUserInfo, userEdit, getUserInfoNewById } from '../../api/user.js';
import { switchH5Login } from '../../api/api.js';
import authLogin from '../../utils/autuLogin.js';
import util from '../../utils/util.js';
import { getCity } from '../../api/api.js';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    parameter: {
      'navbar': '1',
      'return': '1',
      'title': '个人资料',
      'color': true,
      'class': '0'
    },
    userInfo: {},
    loginType: 'h5',//app.globalData.loginType
    userIndex: 0,
    switchUserInfo: [],

    /**省市区所需参数 */
    region: ['省', '市', '区'],
    valueRegion: [0, 0, 0],
    cityId: 0,
    district: [],
    multiArray: [],
    multiIndex: [0, 0, 0],
    isGoIndex: true,
    iShidden: false,
  },
  /**选择地区*/
  bindRegionChange: function (e) {
    console.log('开始改变');
    let multiIndex = this.data.multiIndex, province = this.data.district[multiIndex[0]] || { c: [] }, city = province.c[multiIndex[1]] || { v: 0 }, multiArray = this.data.multiArray, value = e.detail.value;
    console.log(value);
    console.log(province);
    this.setData({
      region: [multiArray[0][value[0]], multiArray[1][value[1]], multiArray[2][value[2]]],
      cityId: city.v,
      valueRegion: [0, 0, 0]
    });
    this.initialize();
  },
  /*拨打电话 */
  goPhone:function(e){
    let phone=e.currentTarget.dataset.phone;
    if(phone){
      wx.makePhoneCall({

        phoneNumber: phone,

      })
    }
    
  },
  /**选择地区列改变 */
  initialize: function () {
    let that = this, province = [], city = [], area = [];
    if (that.data.district.length) {
      let cityChildren = that.data.district[0].c || [];
      let areaChildren = cityChildren.length ? (cityChildren[0].c || []) : [];
      that.data.district.forEach(function (item) {
        province.push(item.n);
      });
      cityChildren.forEach(function (item) {
        city.push(item.n);
      });
      areaChildren.forEach(function (item) {
        area.push(item.n);
      });
      that.setData({
        multiArray: [province, city, area],
      });
    }
  },
  bindMultiPickerColumnChange: function (e) {
    console.log('改变列');
    let that = this, column = e.detail.column, value = e.detail.value, currentCity = this.data.district[value] || { c: [] }, multiArray = that.data.multiArray, multiIndex = that.data.multiIndex;
    multiIndex[column] = value;
    switch (column) {
      case 0:
        let areaList = currentCity.c[0] || { c: [] };
        multiArray[1] = currentCity.c.map((item) => {
          return item.n;
        });
        multiArray[2] = areaList.c.map((item) => {
          return item.n;
        });
        break;
      case 1:
        let cityList = that.data.district[multiIndex[0]].c[multiIndex[1]].c || [];
        multiArray[2] = cityList.map((item) => {
          return item.n;
        });
        break;
      case 2:

        break;
    }
    this.setData({ multiArray: multiArray, multiIndex: multiIndex });
  },
  /**
  * 小程序设置
 */
  Setting: function () {
    wx.openSetting({
      success: function (res) {
        console.log(res.authSetting)
      }
    });
  },
  switchAccounts: function (e) {
    let index = e.currentTarget.dataset.index, userInfo = this.data.switchUserInfo[index], that = this;
    that.setData({ userIndex: index });
    if (that.data.switchUserInfo.length <= 1) return true;
    if (userInfo === undefined) return app.Tips({ title: '切换的账号不存在' });
    if (userInfo.user_type === 'h5') {
      wx.showLoading({ title: '正在切换中' });
      switchH5Login().then(res => {
        wx.hideLoading();
        app.globalData.token = res.data.token;
        app.globalData.expires_time = res.data.time;
        app.globalData.loginType = 'h5';
        app.globalData.userInfo = res.data.userInfo;
        that.getUserInfo();
      }).catch(err => {
        wx.hideLoading();
        return app.Tips({ title: err });
      })
    } else {
      wx.showLoading({ title: '正在切换中' });
      authLogin('routine').then(res => {
        that.getUserInfo();
        wx.hideLoading();
      }).catch(err => {
        wx.hideLoading();
        return app.Tips({ title: err });
      });
    }
  },
  /**
   * 授权回调
  */
  onLoadFun: function () {
    // this.getUserInfo();
    this.getUserInfoNewById();
  },

  /**
   * 退出登录
   * 
  */
  outLogin: function () {
    if (this.data.loginType == 'h5') {
      app.globalData.token = '';
      app.globalData.isLog = false;
      app.globalData.userInfo = {};
      app.globalData.expiresTime = 0;
      wx.showLoading({
        title: '正在退出登录',
      });
      return wx.switchTab({
        url: '/pages/index/index',
        success: function () {
          wx.hideLoading();
        }
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id=options.id;
    this.setData({
      id
    });
    if(!id){
      return app.Tips({ title: '商户信息不存在!' }); wx.navigateBack({ delta: 1 })
    }
    this.getUserInfoNewById();

  },
  /*获取地址列表* */
  getCityList: function () {
    let that = this;
    getCity().then(res => {
      that.setData({ district: res.data });
      that.initialize();
    })
  },

  getPhoneNumber: function (e) {
    var detail = e.detail, cache_key = wx.getStorageSync('cache_key'), that = this;
    if (detail.errMsg == 'getPhoneNumber:ok') {
      if (!cache_key) {
        app.globalData.token = '';
        app.globalData.isLog = false;
        return false;
      }



    } else {
      app.Tips({ title: '取消授权' });
    }
  },

  getUserInfoNewById:function(){
    var that = this;
    getUserInfoNewById(that.data.id).then(res => {
      that.setData({ userInfo: res.data});
    });
  },
  /**
   * 获取用户详情
  */
  getUserInfo: function () {
    var that = this;
    getUserInfo().then(res => {
      that.setData({ userInfo: res.data, switchUserInfo: res.data.switchUserInfo || [] });
      for (let i = 0; i < that.data.switchUserInfo.length; i++) {
        if (that.data.switchUserInfo[i].uid === that.data.userInfo.uid) {
          that.setData({ userIndex: i });
        }
      }
      /**设置地址 */
      var region = [res.data.province, res.data.city, res.data.district];
      that.setData({
        region: region,
        cityId: res.data.city_id,
      });



    });
  },

  /**
  * 上传文件
  * 
 */
  uploadpic: function () {
    var that = this;
    util.uploadImageOne('upload/image', function (res) {
      var userInfo = that.data.switchUserInfo[that.data.userIndex];
      if (userInfo !== undefined) {
        userInfo.avatar = res.data.url;
      }
      that.data.switchUserInfo[that.data.userIndex] = userInfo;
      that.setData({ switchUserInfo: that.data.switchUserInfo });
    });
  },

  /**
   * 提交修改
  */
  formSubmit: function (e) {
    var that = this, value = e.detail.value, userInfo = that.data.switchUserInfo[that.data.userIndex];
    /**添加地址修改数据 */
    value.address = {
      province: that.data.region[0],
      city: that.data.region[1],
      district: that.data.region[2],
      city_id: that.data.cityId,
    };
    if (!value.nickname) return app.Tips({ title: '用户姓名不能为空' });
    value.avatar = userInfo.avatar;
    userEdit(value).then(res => {
      return app.Tips({ title: res.msg, icon: 'success' }, { tab: 3, url: 1 });
    }).catch(msg => {
      return app.Tips({ title: msg || '保存失败，您并没有修改' }, { tab: 3, url: 1 });
    });
  },



})